import BiosafetyAPI from '../../common/api/biosafety/auditmain.api.js';
import doT from '../../../vendor/template/doT.js';
import { auditStateToHtml } from "../../common/json-mapping/state-content-mapping.js";
import { DictionaryType, requestDict } from "../../common/dictionary/dictionary-type.js";

(function (window, document, $) {
    const _isNothing = `<div class="weui-loadmore weui-loadmore_line">
<span class="weui-loadmore__tips">暂无数据</span>
</div>`;
    const _json = Utils.ParsingUrl(window.location);
    const auditmainTemplate = doT.template($('#auditmain-template').text());
    let _vm, _res, index, resTotal = [], listindex = "", _auditTypeData = [], _addressData = [];
    let operatarr = [];
    let categoryInfo = [];
    let _page = {
        pageSize: 10,
        pageIndex: 0,
        totalPages: -1,
    }
    $(function () {
        _vm = new Vue({
            el: "#auditmain",
            data() {
                return {
                    auditList: [],
                    page: { ..._page }
                }
            }
        });
        _initCommand()
        _ctlReturn();
        _returnMain();
        _initSlide();
        pullLoad();
        $('body').attr('data-weui-theme', 'light'); //强制光明模式
        $(".reportForms").on('click', function () {
            window.location.href = './reviewlist.html'
        })
        $(".ranking").on('click', function () {
            window.location.href = './ranking.html'
        })
    });

    //TODO : 命名初始化
    const _initCommand = async () => {
        // 审查类别
        await requestDict(DictionaryType.AUDIT_CATEGORY).then(res => {
            categoryInfo = _.cloneDeep(res.data);
        });
        // 新增按钮
        $('#addsaleorders').on('click', function (e) {
            window.sessionStorage.removeItem("getMainMessage");
            window.sessionStorage.removeItem("getEntryInfo");
            location.href = `../biosafety/auditmaintype.html?v=${Utils.GetTime()}`;
        });

        // 编辑
        $(document).on('click', '#editInfo', function (e) {
            e.stopPropagation()
            let id = $(this).data('id')
            let category = $(this).data('category')
            if(category==1){
                location.href = `./addsaveauditmain.html?v=${Utils.GetTime()}&id=${id}`;
            }else if (category==2){
                location.href = `./addthouauditmain.html?v=${Utils.GetTime()}&id=${id}`;
            }
        });
        
        _addressData = await requestDict(DictionaryType.AUDITADDRESS_TYPE);
        //初始化类型
        requestDict(DictionaryType.AUDIT_TYPE).then(res => {
            $('#type').select2({
                placeholder: '请选择类型...', //默认文字提示
                language: "zh-CN",//汉化
                allowClear: true,//允许清空
                data: res.data.map(item => {
                    return {
                        id: item.value,
                        text: item.displayName
                    }
                }),
            });
            if (_json.type) {
                $('#type').val(_json.type).trigger('change')
            }
            else {
                $('#type').val('').trigger('change')
            }
            _auditTypeData = res.data;
            _search();
        });
        //选择类型加载对应的数据
        $('#type').on('select2:select', function () {
            _search();
        }).on('select2:clear', () => {
            $(`#type`).val('')
            _search();
        });
        //返回公众号主页
        $(document).on('click', '#returnPage', function (e) {
            location.href = `../main.html`;
        })

        // 显示功能可视区
        $(document).on('click', '.ellipsis', function (e) {
            $(document).off("click", ".looksale")
            e.stopPropagation()
            $(".saleElp").siblings('.detail').css('display', 'none')
            $(this).parents(".salesplanstate").siblings('.detail').css('display', 'block')
            index = $(this).parents('.looksale').index()
            let billindex = resTotal[index].bizFormObj.billStatus
            let $opration = $(this).parents('.saleElp').siblings('.detail')
            // 已保存
            if (billindex === 1) {
                $opration.find('.savesale').css('display', 'none')
                $opration.find('.settle').css('display', 'none')
                $opration.find('.generate').css('display', 'none')
            }
            // 已提交
            if (billindex === 2) {
                $opration.find('.subsale').css('display', 'none')
                $opration.find('.settle').css('display', 'none')
                $opration.find('.generate').css('display', 'none')
            }
            // 已审核
            if (billindex === 3) {
                $opration.find('.antiaudit').siblings().css('display', 'none')
                $opration.find('.viewdetails').css('display', 'block')
                $opration.find('.generate').css('display', 'block')
            }
        })

        // 点击功能可视区之外的区域
        $(document).bind("click", function (e) {
            var target = $(e.target);
            if (target.closest(".saleElp").length == 0) { //点击可视区域.saleElp之外的地方触发
                $(".saleElp").siblings('.detail').css('display', 'none')
            }
            // 点击整行跳转详情页面
            $(document).on('click', '.looksale', function (e) {
                $(document).off("click", ".looksale")
                index = $(this).index()
                let type = $('#type').val()
                location.href = `../biosafety/detailsaudit.html?v=${Utils.GetTime()}&id=${resTotal[index].id}&type=${type}`;
            })
        })
        // 点击整行跳转详情页面
        $(document).on('click', '.looksale', function (e) {
            e.stopPropagation()
            $(document).off("click", ".looksale")
            index = $(this).index()
            let type = $('#type').val()
            location.href = `../biosafety/detailsaudit.html?v=${Utils.GetTime()}&id=${resTotal[index].id}&type=${type}`;
        })
    }

    // 搜索
    const _search = () => {
        // 搜索框为空
        if (!Utils.IsNotNull($('#search-index').val())) {
            _initPage()
            _initDataTable()
        }
    }

    $(document).on('submit', '#search_bar form', function (e) {
        _initPage()
        _initDataTable();
        return false;
    })
    // 取消搜索
    $(document).on('click', '#search_cancel', function (e) {
        $('#search-index').val('')
        _initPage()
        _initDataTable()
    })
    // 移除搜索框内容
    $(document).on('click', '#search_clear', function (e) {
        $('#search-index').val('')
        _initPage()
        _initDataTable()
    })

    // 请求列表数据
    const _initDataTable = () => {
        let _data = _vm.page;
        BiosafetyAPI.auditFormBills(Object.assign({
            search: $('#search-index').val(),
            //status: listindex,
            type: $('#type').val()
        }, _data)).then(res => {
            if (res.items.length == 0) {
                return $('#salesplantel').empty().append('<div style="text-align: center;padding-top: 120px;">暂无该审查地点的数据~</div>');
            }
            _page = {
                pageSize: 10,
                pageIndex: _data.pageIndex + 1,
                totalPages: res.totalPages
            }
            _vm._data.page = Object.assign({}, _page);
            res.items.forEach(item=>{
                item.categoryStr = categoryInfo.find(s=>s.value==item.category)?.displayName||'';
                let total = 0;
                item.entries.forEach(key=>{
                    let score = Number(key.weight||0)-Number(key.deduct||0);
                    total += score; 
                })
                item.total = total;
            })
            _res = res.items
            resTotal.push(..._res)
            _res.forEach(ele => {
                let isQualifiedtotal = 0
                //单据状态
                ele.billStatusCh = auditStateToHtml(ele.bizFormObj.billStatus)
                //单据类型
                ele.auditType = _auditTypeData.find(s => s.value == ele.type).displayName
                //审查点
                //ele.auditAddress = _addressData.data.find(s => s.value == ele.adress)?.displayName
                // 是否合格数量合计
                ele.entries.forEach(item => {
                    isQualifiedtotal += item.isQualified == false
                });
                ele.isQualifiedtotal = format(isQualifiedtotal)
                // 去掉时间，只要日期
                ele.createTime = ele.bizFormObj.createTime.replace(/\//g, '-')
            })
            _vm.auditList = []
            _vm.auditList = [..._vm.auditList, ...resTotal];
            $('.looksale:last').css('margin-bottom', '10px')
            $('#salesplantel').empty().append(auditmainTemplate(_vm.auditList));
            $('.looksale').eq(0).find('.saledetail').each(function (index, domele) {
                operatarr = $(domele).text().trim().split(' ')
            })
            $('.looksale:last').css('margin-bottom', '120px')
        });
    }
    // 下拉加载
    const _initSlide = () => {
        //分别设置滑动距离，开始位置，结束位置，和模拟数据的定时器
        let disY, startY, endY, timer, t, pullheight;
        // 触摸开始
        $('#salesplantel').on('touchstart', function (e) {
            startY = e.originalEvent.changedTouches[0].pageY;//开始时的坐标
        });
        // 移动中
        $('#salesplantel').on('touchmove', function (e) {
            $(".saleElp").siblings('.detail').css('display', 'none')
            // 点击整行跳转详情页面
            $(document).on('click', '.looksale', function (e) {
                $(document).off("click", ".looksale")
                index = $(this).index()
                location.href = `../biosafety/detailsaudit.html?v=${Utils.GetTime()}&id=${resTotal[index].id}`;
            })
            endY = e.originalEvent.changedTouches[0].pageY;
            disY = endY - startY;//移动后的坐标减去开始坐标，滑动距离。
            if (isTop() && disY > 0) {
                e.preventDefault();
            }
            if (disY < 60) {
                $('#pull-down').css({
                    height: disY + 'px'//父盒子的高度随着滑动距离变化，有最大值。
                });
            } else {
                $('#pull-down').css({
                    height: 60 + 'px'//父盒子的最大高度
                });
            }
            // 结束时
            $('#salesplantel').on('touchend', function (e) {
                clearInterval(timer);
                endY = e.originalEvent.changedTouches[0].pageY;
                disY = endY - startY;
                if (isTop() && disY > 0) {
                    timer = setInterval(function () {
                        $('#pull-down').css({
                            height: 0 + 'px',//松手后的返回。
                        });
                        clearInterval(timer);
                        _initPage()
                        _initDataTable();//加载数据 
                    }, 300)
                } else {
                    $('#pull-down').css({
                        height: 0 + 'px',//松手后的返回。
                    });
                }
                $('#salesplantel').off('touchend')
            })
        });
    }
    const isTop = () => {
        var t = document.documentElement.scrollTop || document.body.scrollTop;
        return t === 0 ? true : false;
    }

    //TODO : 上拉加载
    const pullLoad = () => {
        // 监听滚动的父容器
        $("body").infinite().on("infinite", function () {
            let _data = _vm._data.page;
            if (_data.pageIndex == _data.totalPages) return;
            let self = this;
            if (self.loading) return;
            self.loading = true;
            setTimeout(function () {
                _initDataTable();
                self.loading = false;
            }, 500);   //模拟延迟
        });
    }
    // 控制返回按钮，返回的页面
    const _ctlReturn = () => {
        if (window.history && window.history.pushState) {
            history.pushState(null, null, document.URL);
            window.addEventListener('popstate', function () {
                history.pushState(null, null, document.URL);
                //跳转列表
                this.window.location = `../main.html`;
            });
        }
    }
    //返回首页
    const _returnMain = () => {
        $('#returnMain').on('click', function () {
            location.href = `../main.html`;
        });
    }

    // 初始化分页
    const _initPage = () => {
        resTotal = []
        _page = {
            pageSize: 10,
            pageIndex: 0,
            totalPages: -1,
        }
        _vm._data.page = Object.assign({}, _page);
    }
    // 千分位
    const format = (num) => {
        var reg = /\d{1,3}(?=(\d{3})+$)/g;
        return (num + '').replace(reg, '$&,');
    }
})(window, document, jQuery)